/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.core.service;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Map.Entry;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoFilter;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.springframework.osgi.extender.internal.dependencies.startup.ServiceDependency;
import org.springframework.util.StringUtils;

import com.cqcis.uip.base.framework.FrameworkConstants;
import com.cqcis.uip.base.framework.PropertiesConfigService;
import com.cqcis.uip.base.framework.base.adaptor.AbstractRegisteredService;
import com.cqcis.uip.base.framework.base.adaptor.AbstractSocketService;
import com.cqcis.uip.base.framework.common.ControlMsg;
import com.cqcis.uip.base.framework.common.Task;
import com.cqcis.uip.base.framework.core.BundleInfoDescription;
import com.cqcis.uip.base.framework.core.Endpoint;
import com.cqcis.uip.base.framework.core.RegisteredService;
import com.cqcis.uip.base.framework.core.RegisteredServiceFindService;
import com.cqcis.uip.base.framework.core.RegisteredServiceProperty;
import com.cqcis.uip.base.framework.core.ResetServiceManage;
import com.cqcis.uip.base.framework.core.ServiceState;
import com.cqcis.uip.base.framework.core.StateManage;
import com.cqcis.uip.base.framework.core.cluster.ActiveClusterService;
import com.cqcis.uip.base.framework.core.cluster.ClusterStub;
import com.cqcis.uip.base.framework.core.cluster.ClusterSupportSelector.StubState;
import com.cqcis.uip.base.framework.core.config.PropertiesConfig;
import com.cqcis.uip.base.framework.core.config.PropertiesRepositoryService;
import com.cqcis.uip.base.framework.service.EncryptorService;
import com.cqcis.uip.base.framework.service.ListTasksService;
import com.cqcis.uip.base.framework.service.ResetService;
import com.cqcis.uip.base.framework.utils.BundleStatePrintUtil;
import com.cqcis.uip.base.framework.utils.DebugUtil;
import com.cqcis.uip.base.framework.utils.EndpointGenerator;
import com.cqcis.uip.base.framework.utils.LogConfigurationUtil;
import com.cqcis.uip.base.framework.utils.LogServiceThreadPoolExecutor;
import com.cqcis.uip.base.framework.utils.StringUtil;
import com.cqcis.uip.base.framework.utils.LogServiceThreadFactory.LogThread;
import com.cqcis.uip.base.framework.utils.LogServiceThreadPoolExecutor.LogThreadPoolExecutor;
import com.cqcis.uip.base.logadaptor.LogConfiguration;

/**
 * 注册服务支持命令, 提供命令支持
 * 
 * @author huangmy
 * @date   2008-4-26
 */
public class RegisteredServiceSupport implements BundleActivator, CommandProvider  {
    private BundleContext context;// 上下文
    private ServiceRegistration commandRegistration; // 命令注册
    
	public void start(BundleContext context) throws Exception {
		this.context = context;
		this.commandRegistration = context.registerService(CommandProvider.class.getName(), this,
				null);	
	}

	public void stop(BundleContext context) throws Exception {		
		if (this.commandRegistration != null) {
			this.commandRegistration.unregister();
		}
	}
	
	private ActiveClusterService getActiveClusterService() {
		ServiceReference sr = context.getServiceReference(ActiveClusterService.class.getName());
		if (sr == null) {
			return null;
		}
		
		return (ActiveClusterService)context.getService(sr);
	}
	
	/**
	 * 集群辅助命令
	 * 
	 * @param ci
	 */
	public void _cl(CommandInterpreter ci) {
		_cluster(ci);
	}
	
	/**
	 * 集群辅助
	 * 
	 * @param ci
	 */
	public void _cluster(CommandInterpreter ci) {
		String cmd = ci.nextArgument();
		cmd = StringUtil.trimWhiteToNull(cmd);
		
		ActiveClusterService activeClusterService = getActiveClusterService();
		if (activeClusterService == null) {
			ci.println("ERROR: Cluster Service is NOT Active.");
			return;
		}
		
		if ("active".equalsIgnoreCase(cmd)) { // 激活
			String param = ci.nextArgument();
			if (StringUtil.hasText(param)) { // 某个ID
				long id = Long.valueOf(param);
				activeClusterService.active(id);
			} else {
				activeClusterService.active();
			}
		} else if ("print".equalsIgnoreCase(cmd)) { // PRINT
			Collection<ClusterStub> stubs = activeClusterService.getStubs();
			
			String args = ci.nextArgument();
			args = StringUtil.trimWhiteToNull(args);
			
			if (args == null) {				
				ci.print(createClusterPrintTitle(false));
				for (ClusterStub stub : stubs) {
					ci.print(createClusterPrint(stub, false));
				}
				ci.println();
			} else {
				long id = Long.valueOf(args);
				ci.print(createClusterPrintTitle(true));
				for (ClusterStub stub : stubs) {
					if (id == stub.getId()) {
						ci.print(createClusterPrint(stub, true));
					}
				}
				ci.println();
			}			
		} else if ("clear".equalsIgnoreCase(cmd)) { // CLEAR
			Collection<ClusterStub> stubs = activeClusterService.getStubs();
			for (ClusterStub stub : stubs) {
				if (stub.getState() != StubState.ACTIVE) {
					activeClusterService.remove(stub.getSi().toString());
				}
			}
		}
	}
	
	private String createClusterPrint(ClusterStub stub, boolean detail) {
		String nodes = stub.getSiKey();
		String note = stub.getStateNode().toString();
		note = note.length() > 40 ? note.substring(0, 40) : note;		
		String t = null;
		
		if (detail) {
			t = String.format("%6s  %72s  %8s", 
					stub.getId(), stub.getSi().toString(), stub.getState());
		} else {
			t = String.format("%6s  %12s  %8s  %s", 
					stub.getId(), nodes, stub.getState(), note);
		}
		
		t = t + "\n";
		
		return t;
	}
	
	private String createClusterPrintTitle(boolean detail) {		
		String t = null;
		if (detail) {
			t = String.format("%6s  %72s  %8s", 
					"ID", "NODES", "STATE");
			t = t + "\n";
			for (int i = 0; i < 46; i ++) {
				t = t + "--";
			}
		} else {
			t = String.format("%6s  %12s  %8s  %s", 
					"ID", "NODES", "STATE", "NOTE");
			t = t + "\n";
			for (int i = 0; i < 19; i ++) {
				t = t + "--";
			}
		}
		
		t = t + "\n";
		return t;
	}
	
	private ThreadGroup getTopThreadGroup() {
		ThreadGroup topGroup = Thread.currentThread().getThreadGroup();
		if (topGroup != null) {
			while (topGroup.getParent() != null) {
				topGroup = topGroup.getParent();
			}
		}
		return topGroup;
	}
	
	/**
	 * session 状态
	 * 
	 * @param ci
	 */
	public void _ses(CommandInterpreter ci) {
		RegisteredServiceFindService findService = getRegisteredServiceFindService();
		if (findService == null) {
			ci.println("ERROR: can't find RS Repo service.");
			return;
		}
		
		String idStr = ci.nextArgument();
		idStr = StringUtil.trimWhiteToNull(idStr);		
		if (idStr == null) {
			// print usage
			ci.println("USAGE: ses 'control id'");
			return;
		}
		
		long bundleId = Long.parseLong(idStr); // BUNDLE ID		
		RegisteredService rs = findService.getRegisteredService(bundleId); 
		if (rs == null) {
			ci.println("ERROR: can't find RS for id " + bundleId);
			return;
		}
		
		if (!(rs instanceof AbstractSocketService)) {
			return;
		}
		
		AbstractSocketService srs = (AbstractSocketService)rs;
		Map<String, IoFilter> filters = srs.getFilters();
		if (filters == null) {
			return;
		}
		
		ci.println(createSesStr("NAME", "CLASSTYPE"));
		ci.println("---------------------------------------------------------");
		for (Entry<String, IoFilter> entry : filters.entrySet()) {
			ci.println(createSesStr(entry.getKey(), entry.getValue().getClass().getName()));
		}
	}
	
	private String createSesStr(String name, String type) {
		String t = String.format("%36s    %s", name, type);
		return t;
	}
	
	/**
	 * find thread
	 * 
	 * @param ci
	 */
	public void _ft(CommandInterpreter ci) {
		String threadName = ci.nextArgument(); // Session id 描述
		threadName = StringUtil.trimWhiteToNull(threadName);
		if (threadName == null) {
			return;
		}
		
		ThreadGroup tg = getTopThreadGroup();
		Thread[] threads = new Thread[tg.activeCount()];
		int count = tg.enumerate(threads, true);
				
		for (int i = 0; i < count; i ++) {
			Thread t = threads[i];
			if (t == null) {
				continue;
			}
			String name = t.getName();
			name = name.toLowerCase();
			threadName = threadName.toLowerCase();			
			if (name.indexOf(threadName) >= 0) {
				String s = String.format("%6s  %6s  %6s  %s", t.getId(), t.getPriority(), t.getState(), t.getName());
				ci.println(s);
			}
		}
	}
	
	/**
	 * 接收到的未决buffer
	 * 
	 * @param ci
	 */
	public void _pbs(CommandInterpreter ci) {
		String sessionIdStr = ci.nextArgument(); // Session id 描述
		List<IoSession> ss = findIoSession(ci, sessionIdStr);
		if (ss != null) {
			for (IoSession s : ss) {
				ByteBuffer buf = (ByteBuffer) s.getAttribute(CumulativeProtocolDecoder.class
			            .getName()
			            + ".Buffer");
				if (buf == null) {
					continue;
				}
				int oldpos = buf.position();
				byte[] dst = new byte[buf.limit() - buf.position()];
				buf.get(dst);
				buf.position(oldpos);
				
				StringBuffer sb = new StringBuffer();
				sb.append("\n");
				for (int i = 0; i < dst.length; i ++) {
					byte b = dst[i];
					sb.append(StringUtil.toHexString(b, false));
					if (i > 0 && i%32 == 0) {
						sb.append("\n");
					}
				}
				
				ci.println(sessionIdStr + "'s Pending Recv Buffer: " + sb.toString()
						+ "\nSTRING: " + new String(dst));
			}
		}
	}
	
	/**
	 * 包状态
	 * 
	 * @param ci
	 */
	public void _ps(CommandInterpreter ci) {
		ServiceReference rf = this.context.getServiceReference(PackageAdmin.class.getName());
		if (rf == null) {
			ci.print("WARN: PackageAdmin is not exist.");
			return;
		}
		
		String packageName = ci.nextArgument();
		if (packageName == null) {
			ci.print("WARN: package is needed.");
			return;
		}
		
		StringBuffer buffer = new StringBuffer();
		
		PackageAdmin pa = (PackageAdmin)this.context.getService(rf);
		if (pa != null) {			
			ExportedPackage[] eps = pa.getExportedPackages(packageName);
			if (eps != null && eps.length > 0) {
				List<Bundle> exportBundles = new ArrayList<Bundle>();
				List<Bundle> importBundles = new ArrayList<Bundle>();
				boolean removalPending = false;
				
				for (ExportedPackage ep : eps) {
					Bundle eb = ep.getExportingBundle(); // 导出BUNDLE
					if (eb != null) {
						exportBundles.add(eb);
					}
										
					Bundle[] ibs = ep.getImportingBundles(); // 导入BUNDLE
					if (ibs != null && ibs.length > 0) {
						for (Bundle ib : ibs) {
							if (ib != null) {
								importBundles.add(ib);
							}							
						}
					}
					
					removalPending = ep.isRemovalPending(); // 该包所属的BUNDLE是否已经UNINSTALL					
				}
				
				buffer.append("[export bundles]:\n");
				for (Bundle eb : exportBundles) {
					buffer.append(createBundleStr(eb)).append("\n");
				}
				
				buffer.append("[import bundles]:\n");
				for (Bundle ib : importBundles) {
					buffer.append(createBundleStr(ib)).append("\n");
				}
				
				buffer.append("[package status]:\n")
				      .append(removalPending ? "RemovalPending" : "Normal")
				      .append("\n");
			} else {
				buffer.append("Can't find info for '")
				      .append(packageName).append("'")
				      .append("\n");
			}
			
			ci.print(buffer.toString());
		}
	}
	
	private Bundle getBundleFromCI(CommandInterpreter ci) {
		String idStr = ci.nextArgument();
		idStr = StringUtil.trimWhiteToNull(idStr);
		if (idStr == null) {
			ci.print("WARN: id is needed.");
			return null;
		}
		
		long id = Long.parseLong(idStr);
		return this.context.getBundle(id);
	}
	
	/**
	 * 查看bundle的详细情况: 
	 * id name location state import export import-service export-service
	 * dependencies dependents
	 * 
	 * @param ci
	 */
	public void _info(CommandInterpreter ci) {
		Bundle bundle = getBundleFromCI(ci);
		if (bundle == null) {
			ci.print("\nWARN: can't find bundle for this.");
			return;
		}
		
		BundleInfoDescription desc = new BundleInfoDescription(this.context);
		
		ci.print(desc.getDescription(bundle));
	}
	
	/**
	 * 列出服务处理状况描述
	 * 
	 * @param ci
	 */
	public void _lt(CommandInterpreter ci) {
		ServiceReference sr = this.context.getServiceReference(ListTasksService.class.getName());
		if (sr == null) {
			ci.print("ERROR: can't find the 'ListTasksService', you can't use the command in the moment.");
			return;
		}
		
		ListTasksService lts = (ListTasksService)this.context.getService(sr);
		if (lts != null) {
			String d = lts.description();
			ci.print(d);
		}
	}
	
	/**
	 * 
	 * @return
	 */
	private String getTPCommandUSage() {
		return "USAGE: tp [contrlid][all][print/pt poolid][printStackTrace/pst poolthreadid][printStackTraceSys/pstsys theadsysid]" +
				"[interrupt/it [-thread/-t/-threadsys/-tsys poolthreadid][-pool/-p poolid]]";
	}
	
	/**
	 * 查看线程池
	 * 
	 * @param ci
	 */
	public void _tp(CommandInterpreter ci) {
		RegisteredServiceFindService findService = getRegisteredServiceFindService();
		if (findService == null) {
			ci.println("ERROR: can't find RS Repo service.");
			return;
		}
		
		String idStr = ci.nextArgument();
		idStr = StringUtil.trimWhiteToNull(idStr);		
		if (idStr == null) {
			// print usage
			ci.println(getTPCommandUSage());
			return;
		}
		
		if ("all".equalsIgnoreCase(idStr)) {// 显示所有的线程池
			Collection<RegisteredService> rss = findService.getRegisteredServices();
			if (rss != null) {
				List<ThreadPoolExecutor> tpes = new ArrayList<ThreadPoolExecutor>();
				for (RegisteredService rs : rss) {
					tpes.addAll(getTPEsForRS(rs));					
				}
				int tpeSize = tpes.size(); // 线程池数
	    		ci.println("All threadPools Number: " + tpeSize);	    		
	    		ci.print(createTPEPrintTitle());
				ci.print(getThreadPoolDescForRSNoTitle(tpes));
			}
			return;
		} else if ("print".equalsIgnoreCase(idStr) || "pt".equalsIgnoreCase(idStr)) {// 显示线程池的线程详情以及线程数
			String id = ci.nextArgument();
			String poolId = StringUtil.trimWhiteToNull(id);
			ci.println("I. ThreadPool Status: "); 
			ci.print(createTPEPrintTitle());
			List<ThreadPoolExecutor> tpes = new ArrayList<ThreadPoolExecutor>();
			ThreadPoolExecutor tpe = LogServiceThreadPoolExecutor.getCurrentThreadPoolExecutorById(poolId);
			if (tpe == null) {
				ci.println("ERROR: Can't find threadpool by id: " + poolId);
				return;
			}
			tpes.add(tpe);
    		ci.println(getThreadPoolDescForRSNoTitle(tpes)); 
    		
    		ci.println("II. Thread Status: "); 
    		// 显示每个线程的状态
    		Collection<Thread> threads = LogServiceThreadPoolExecutor.getAllActiveThreadsFrom(tpe);
    		ci.println(createThreadStatusTitle());
    		if (threads != null) {
    			for (Thread t : threads) {    				
    				ci.println(getThreadDesc(t));    				
    			}
    		}    		
			return;
		} else if ("printStackTrace".equalsIgnoreCase(idStr) || "pst".equalsIgnoreCase(idStr)) {// 显示线程堆栈
			String id = ci.nextArgument();
			Thread t = getThreadFromId(id);
			if (t == null) {
			    ci.println("ERROR: Can't find thread by id: " + id);
			    return;
			}
			ci.println("I. Thread Status: "); 
    		ci.println(createThreadStatusTitle());
    		// 找到线程
			ci.println(getThreadDesc(t));
			ci.println();
    		ci.println("II. StackTrace: "); 
			String s = DebugUtil.getCurrentStackTrace(t.getStackTrace());
			ci.println(s);			
			if (t instanceof LogThread) {
				ci.println("III. Thread Attributes: "); 
				LogThread lt = (LogThread)t;
				Map<String, Object> atts = lt.getAttributes();
				for (Entry<String, Object> entry : atts.entrySet()) {
					ci.println("\t" + entry.getKey() + "\t" + entry.getValue()); 
				}
			}
			return;
		} else if ("printStackTraceSys".equalsIgnoreCase(idStr) || "pstsys".equalsIgnoreCase(idStr)) {
			String id = ci.nextArgument();
			Thread t = null;
			
			ThreadGroup tg = getTopThreadGroup();
			Thread[] threads = new Thread[tg.activeCount()];
			int count = tg.enumerate(threads, true);
			for (int i = 0; i < count; i ++) {
				Thread tf = threads[i];
				if (tf != null && tf.getId() == Long.parseLong(id)) {
					t = tf;
					break;
				}
			}
			
			if (t == null) {
			    ci.println("ERROR: Can't find thread by id: " + id);
			    return;
			}
			ci.println("I. Thread Status: "); 
    		ci.println(createThreadStatusTitle());
    		// 找到线程
			ci.println(getThreadDesc(t));
			ci.println();
    		ci.println("II. StackTrace: "); 
			String s = DebugUtil.getCurrentStackTrace(t.getStackTrace());
			ci.println(s);			
			if (t instanceof LogThread) {
				ci.println("III. Thread Attributes: "); 
				LogThread lt = (LogThread)t;
				Map<String, Object> atts = lt.getAttributes();
				for (Entry<String, Object> entry : atts.entrySet()) {
					ci.println("\t" + entry.getKey() + "\t" + entry.getValue()); 
				}
			}
			return;
		} else if ("interrupt".equalsIgnoreCase(idStr) || "it".equalsIgnoreCase(idStr)) {// 中断
			String param = ci.nextArgument();
			String id = ci.nextArgument();
			if ("-thread".equalsIgnoreCase(param) || "-t".equalsIgnoreCase(param)) { // 中断线程
				Thread t = getThreadFromId(id);
				if (t == null) {
				    ci.println("ERROR: Can't find thread by id: " + id);
				    return;
				}
				t.interrupt();// 中断
				ci.println("interrupt " + ((LogThread)t).getLogThreadId() + " success.");
			} else if ("-pool".equals(param) || "-p".equalsIgnoreCase(param)) {// 中断线程池, 只是将线程池中的所有活动线程中断，并不会shutdown线程池
				String poolId = StringUtil.trimWhiteToNull(id);
				ThreadPoolExecutor tpe = LogServiceThreadPoolExecutor.getCurrentThreadPoolExecutorById(poolId);
				if (tpe == null) {
					ci.println("ERROR: Can't find threadpool by id: " + poolId);
					return;
				}
				Collection<Thread> threads = LogServiceThreadPoolExecutor.getAllActiveThreadsFrom(tpe);		
				if (threads != null) {
					for (Thread t : threads) {
						t.interrupt();
						ci.println("interrupt " + ((LogThread)t).getLogThreadId() + " success.");
					}
				}
			} else if ("-threadsys".equalsIgnoreCase(param) || "-tsys".equalsIgnoreCase(param)) {
				ThreadGroup tg = getTopThreadGroup();
				Thread[] threads = new Thread[tg.activeCount()];
				int count = tg.enumerate(threads, true);
				for (int i = 0; i < count; i ++) {
					Thread t = threads[i];
					if (t != null && t.getId() == Long.parseLong(id)) {
						t.interrupt();// 中断
						ci.println("interrupt thread " + id + " success.");
						return;
					}
				}
			} else {
				ci.println("ERROR: Command Format Error, " + getTPCommandUSage());
			}
			return;
		}
		
		long bundleId = Long.parseLong(idStr); // BUNDLE ID		
		RegisteredService rs = findService.getRegisteredService(bundleId); 
		if (rs == null) {
			ci.println("ERROR: can't find RS for id " + bundleId);
			return;
		}
		
		// 当前RS上的所有线程池
    	Collection<ThreadPoolExecutor> tpes = getTPEsForRS(rs);
    	if (tpes != null) {
    		int tpeSize = tpes.size(); // 线程池数
    		ci.println(rs.getName() + " 's threadPool Number: " + tpeSize);
    		ci.print(createTPEPrintTitle());
    		ci.println(getThreadPoolDescForRSNoTitle(tpes)); 
    	} else {
    		ci.println(rs.getName() + " 's threadPool Number: 0");
    	}
	}
	
	/**
	 * 从ID获取线程
	 * 
	 * @param id
	 * @return
	 */
	private Thread getThreadFromId(String id) {
		String[] ss = id.split(":");
		if (ss == null || ss.length < 2) {			
			return null;
		}		
		
		String poolId = StringUtil.trimWhiteToNull(ss[0]); // 线程池Id
		
		ThreadPoolExecutor tpe = LogServiceThreadPoolExecutor.getCurrentThreadPoolExecutorById(poolId);
		if (tpe == null) {			
			return null;
		}
		Collection<Thread> threads = LogServiceThreadPoolExecutor.getAllActiveThreadsFrom(tpe);		
		if (threads != null) {
			for (Thread t : threads) {
				String tId = ((LogThread)t).getLogThreadId();
				if (tId.equalsIgnoreCase(id)) {
					return t;
				}
			}
		}
		return null;
	}
	
	/**
	 * 线程描述
	 * 
	 * @param t
	 * @return
	 */
	private String getThreadDesc(Thread t) {
		String name = t.getName(); // 名称
		int priority = t.getPriority(); // 级别
		State state = t.getState(); // 状态
		ThreadGroup group = t.getThreadGroup(); // 线程组
		ClassLoader cl = t.getContextClassLoader(); // 线程上下文类加载器
		String tId = (t instanceof LogThread) ? ((LogThread)t).getLogThreadId() : String.valueOf(t.getId());
		
		return createThreadStatusParam(tId, name, priority, state.toString(), 
				group.getName(), cl.toString());
	}
	
	/**
	 * 所有的线程池
	 * 
	 * @param rs
	 * @return
	 */
	private Collection<ThreadPoolExecutor> getTPEsForRS(RegisteredService rs) {
		LogConfiguration configRS = rs.getLogConfiguration();    	  	
		// 当前RS上的所有线程池
    	return LogConfigurationUtil.getTPEsFor(configRS);
	}
	
	/**
	 * RS线程池描述
	 * 
	 * @param rs
	 * @return
	 */
	private String getThreadPoolDescForRSNoTitle(Collection<ThreadPoolExecutor> tpes) {
		String desc = "";		
		for (ThreadPoolExecutor tpe : tpes) {
			int coreSize = tpe.getCorePoolSize(); // 核心线程数
			int maxSize = tpe.getMaximumPoolSize(); // 最大线程数
			int currentSize = tpe.getPoolSize(); // 当前池中线程数
			int largestSize = tpe.getLargestPoolSize(); // 曾经位于池中的最大线程数
			int activeCount = tpe.getActiveCount(); // 活动线程数
			long keepAliveTime = tpe.getKeepAliveTime(TimeUnit.SECONDS); // 保持活动时间
			long taskCount = tpe.getTaskCount(); // 任务总数, 包含已经完成的
			long completeTaskCount = tpe.getCompletedTaskCount(); // 已经完成的任务总数
			int waitQueueSize = tpe.getQueue().size(); // 等待执行的runnable
			String tpeId = ((LogThreadPoolExecutor)tpe).getId();// 线程池ID
			String tpeName = ((LogThreadPoolExecutor)tpe).getName(); // 线程池名称
			
			String s = createTPEPrintParam(tpeId,coreSize, maxSize, currentSize, largestSize, activeCount, keepAliveTime, 
					taskCount, completeTaskCount, waitQueueSize,tpeName);
			desc = desc + s;    			
		}
		
		return desc;
	}
	
	private String createTPEPrintTitle() {
		String t = String.format("%6s  %6s  %6s  %7s  %7s  %6s  %10s  %8s  %13s  %13s  %s", "POOLID", "CORE", "MAX", "CURRENT", "LARGEST", 
				"ACTIVE", "ALIEVETIME", "RUNABLES", "COMPRUNNABLES", "WAITRUNNABLES", "POOLNAME");
		t = t + "\n";
		for (int i = 0; i < 37; i ++) {
			t = t + "---";
		}
		t = t + "\n";
		return t;
	}
	
	private String createTPEPrintParam(String tpeId, int coreSize,int maxSize,int currentSize,int largestSize,
			int activeCount,long keepAliveTime,long taskCount,long completeTaskCount,int waitQueueSize, String tpeName) {
		String t = String.format("%6s  %6s  %6s  %7s  %7s  %6s  %10s  %8s  %13s  %13s  %s", tpeId, coreSize, maxSize, currentSize,
				largestSize, activeCount, keepAliveTime + "s", taskCount, completeTaskCount, waitQueueSize, tpeName);
		
		return t + "\n";
	}
	
	/**
	 * 线程状态显示题目
	 * 
	 * @return
	 */
	private String createThreadStatusTitle() {
		String threadname = "THREADNAME";
		threadname = threadname.length() > 24 ? threadname.substring(0, 24) : threadname;
		String state = "STATE";
		state = state.length() > 8 ? state.substring(0, 8) : state;
		String priority = "PRIORITY";
		String group = "GROUP";
		group = group.length() > 16 ? group.substring(0, 16) : group;
		
		String t = String.format("%8s  %24s  %8s  %8s  %16s %s", "ID",threadname, priority, state, 
				group,  "CONTEXTCLASSLOADER");
		t = t + "\n";
		for (int i = 0; i < 31; i ++) {
			t = t + "---";
		}
		return t;
	}
	
	/**
	 * 线程状态显示
	 * 
	 * @param threadname
	 * @param priority
	 * @param state
	 * @param group
	 * @param contextClassLoader
	 * @return
	 */
	private String createThreadStatusParam(String threadId, String threadname, int priority, String state, String group, String contextClassLoader) {
		threadname = threadname.length() > 24 ? threadname.substring(0, 24) : threadname;
		state = state.length() > 8 ? state.substring(0, 8) : state;
		group = group.length() > 16 ? group.substring(0, 16) : group;
		return String.format("%8s  %24s  %8s  %8s  %16s %s", threadId, threadname, priority, state, 
				group, contextClassLoader);
	}
	
	/**
	 * 刷新指定的缓存
	 * 
	 * @param ci
	 */
	public void _flush(CommandInterpreter ci) {
		ResetServiceManage rsm = getResetServiceManage();
		if (rsm == null) {
			return;
		}
		
		String idStr = ci.nextArgument();
		idStr = StringUtil.trimWhiteToNull(idStr);
		if (idStr == null) {
			// 显示所有的cache
			ci.println(rsm.getDescription());
			return;
		}
		
		if ("all".equalsIgnoreCase(idStr)) {
			// 刷新所有的缓存
			Collection<ResetService> rss = rsm.getAll();
			if (rss != null) {
				for (ResetService s : rss) {
					try {
						s.reset();
					} catch (Exception e) {
						ci.printStackTrace(e);
					}
				}
			}
			
			return;
		} else if ("print".equalsIgnoreCase(idStr)) {
			String printIdStr = ci.nextArgument();
			long id = Long.parseLong(printIdStr);
			ResetService s = rsm.getResetService(String.valueOf(id));
			if (s != null) {
				try {
					Map<?, ?> cache = s.getCache();
					String t = String.format("%-32s    %s", "CACHE-KEY", "CACHE-VALUE");					
					ci.println(t);
					t = "------------------------------------------------";
					ci.println(t);
					if (cache != null) {
						for (Entry<?, ?> entry : cache.entrySet()) {
							t = String.format("%-32s    %s", entry.getKey(), entry.getValue());
							ci.println(t);
						}
					}
				} catch (Exception e) {
					ci.printStackTrace(e);
				}
			}
			
			return;
		} else if ("find".equalsIgnoreCase(idStr)) {
			String printIdStr = ci.nextArgument();
			long id = Long.parseLong(printIdStr);
			String expression = ci.nextArgument();
			if (!StringUtil.hasText(expression)) {
				ci.println("USAGE: flush find [id] [expression]");
				return;
			}
			ResetService s = rsm.getResetService(String.valueOf(id));
			if (s != null) {
				try {
					Map<?, ?> cache = s.getCache();
					String t = String.format("%-32s    %s", "CACHE-KEY", "CACHE-VALUE");					
					ci.println(t);
					t = "------------------------------------------------";
					ci.println(t);
					if (cache != null) {
						for (Entry<?, ?> entry : cache.entrySet()) {
							String key = entry.getKey().toString();
							if (key.indexOf(expression) >= 0) {
								t = String.format("%-32s    %s", key, entry.getValue());
								ci.println(t);
							}
						}
					}
				} catch (Exception e) {
					ci.printStackTrace(e);
				}
			}
			
			return;
		}
		
		long id = Long.parseLong(idStr);
		ResetService s = rsm.getResetService(String.valueOf(id));
		if (s != null) {
			try {
				s.reset();
			} catch (Exception e) {
				ci.printStackTrace(e);
			}
		}
	}
	
	private ResetServiceManage getResetServiceManage() {
		ServiceReference ssmRf = context.getServiceReference(ResetServiceManage.class.getName());
        if (ssmRf != null) {
        	return (ResetServiceManage) context.getService(ssmRf);
        }
        
        return null;
	}
	
	private String createBundleStr(Bundle bundle) {		
		return BundleStatePrintUtil.print(bundle);
	}
	
	private String createStateStr(String id, String state, String bundleName) {
		String t = String.format("%4s    %22s    %s", id, state, bundleName);
		return t;
	}
	
	/**
	 * Spring 服务状态
	 * 
	 * @param ci
	 */
	public void _sss(CommandInterpreter ci) {
		StateManage ssm = getStateManageService();
		if (ssm == null) {
			ci.print("Can't find 'StateManageService', you can't use the command in the moment.");
			return;
		}
		
		StringBuffer buffer = new StringBuffer();
		buffer.append(createStateStr("ID", "STATE", "BUNDLE"))
				      .append("\n");
		
		String idStr = ci.nextArgument();
		if (idStr != null) { // 有参数
			long id = -1;
			try {
				id = Long.parseLong(idStr);
			} catch (RuntimeException e) {
				buffer.append("Can't find bundle for ").append(idStr).append("\n");
				ci.print(buffer.toString());
				return;
			}
			
			ServiceState state = ssm.getState(id);
			if (state != null) {
				buffer.append(createStateStr(String.valueOf(state.getBundleId()), state.getState().toString(), state
						.getBundleName())).append("\n");
				//message				
				if (state.getMessage() != null) {
					buffer.append("[MESSAGE]\n");
					buffer.append(state.getMessage());
					buffer.append("\n");
				}
				
				// exception				
				if (state.getThrowable() != null) {
					buffer.append("[EXCEPTION]\n");
					StringWriter sw = new StringWriter();
					state.getThrowable().printStackTrace(new PrintWriter(sw));
					buffer.append(sw);
				}
				
				//UnsatisfiedDependencies				
				if (state.getUnsatisfiedDependencies() != null 
						&& state.getUnsatisfiedDependencies().getUnsatisfied() != null 
						&& state.getUnsatisfiedDependencies().getUnsatisfied().size() > 0) {
					buffer.append("[UNSATISFIEDDEPENDENCIES]\n");
					Set<ServiceDependency> unsdps = state.getUnsatisfiedDependencies().getUnsatisfied();
					for (Iterator<ServiceDependency> it = unsdps.iterator(); it.hasNext();) {
						ServiceDependency sd = it.next();				
						buffer.append(sd).append("\n");
					}
				}
			}			
		} else {
			List<ServiceState> states = ssm.getStates();
			if (states != null) {
				for (ServiceState state : states) {
					buffer.append(createStateStr(String.valueOf(state.getBundleId()), state.getState().toString(), state
									.getBundleName())).append("\n");
				}
			}
		}
		
		ci.print(buffer.toString());
	}
	
	/**
	 * 状态管理服务
	 * 
	 * @return
	 */
	private StateManage getStateManageService() {
		ServiceReference ssmRf = context.getServiceReference(StateManage.class.getName());
        if (ssmRf != null) {
        	return (StateManage) context.getService(ssmRf);
        }
        
        return null;
	}
	
	/**
	 * 模拟生成、发送task的命令
	 * 
	 * @param ci
	 */
	public void _st(CommandInterpreter ci) {
		RegisteredServiceFindService findService = getRegisteredServiceFindService();
		if (findService == null) {
			ci.println("ERROR: can't find RS Repo service.");
			return;
		}
		
		String taskId = ci.nextArgument();
		String idStr = ci.nextArgument();
		idStr  = StringUtil.trimWhiteToNull(idStr);
		RegisteredService rs = null;
				
		Task task = new Task(taskId);
		task.route().from(EndpointGenerator.generate(-9999, null));
		if ("-i".equalsIgnoreCase(idStr)) {// 参数
			idStr = ci.nextArgument();
			long rsid = Long.parseLong(idStr);
			rs = findService.getRegisteredService(rsid);
			if (rs == null) {
				ci.println("Can't find RS for the id '" + rsid + "'.");
				return;
			}			
			
			task.route().to(rs.getEndpoints().iterator().next());
		} else {
			long id = Long.parseLong(idStr);
			Map<String, String> props = null;
			String properties = ci.nextArgument();
			if (properties != null) {
				props = new HashMap<String, String>();
				
				StringTokenizer st = new StringTokenizer(properties, ",");
				while (st.hasMoreTokens()) {
					String s = st.nextToken();
					String[] ss = s.split("=");				
					props.put(ss[0], ss[1]);
				}
			}
						
			Endpoint to = EndpointGenerator.generate(id, props);
			rs = findService.getRegisteredService(to);
			if (rs == null) {
				ci.println("Can't find RS for the URI: " + to );
				return;
			}	
			
			task.route().to(to);
		}
				
		try {
			rs.scheduleSync(task);
			if (task.getState() == com.cqcis.uip.base.framework.common.State.ERROR) {
				ci.println("ST RESULT >>> \n\t" + task);
			}
		} catch (Exception e) {
			ci.printStackTrace(e);
		}
	}
		
	/**
	 * 关闭连接, close session
	 * 
	 * @param ci
	 */
	public void _cs(CommandInterpreter ci) {
		String sessionIdStr = ci.nextArgument(); // Session id 描述
		List<IoSession> ss = findIoSession(ci, sessionIdStr);
		if (ss != null) {
			for (IoSession s : ss) {
				s.write(new ControlMsg("session closed by 'cs' command.")).join();
				s.close().join();
				ci.println("close session '" + sessionIdStr + " success.");
			}
		}
	}
	
	private List<IoSession> findIoSession(CommandInterpreter ci, String sessionIdStr) {
		if (!StringUtil.hasText(sessionIdStr)) {
			ci.println("ERROR: invalid params.");
			return null;
		}
		
		String[] ss = sessionIdStr.split(":");
		if (ss == null || ss.length != 2) {
			ci.println("ERROR: invalid string.");
			return null;
		}
		
		for (int i = 0; i < ss.length; i ++) {
			ss[i] = StringUtil.trimWhiteToNull(ss[i]);
			String s = ss[i];			
			if (s == null) {
				ci.println("ERROR: invalid string, params can't be null.");
				return null;
			}
		}
		
		long rsId = Long.parseLong(ss[0]); // 接口控制ID
		String sessionId = ss[1]; // session ID
		
		RegisteredService rs = getRegisteredService(rsId);
		if (rs == null) {
			ci.println("ERROR: can't find RS for id '" + rsId + "'.");
			return null;
		}
		
		if (!(rs instanceof AbstractSocketService)) {
			ci.println("ERROR: the RS for id '" + rsId 
					+ "' is not the instance of SOCKET, can't find sessions for this.");
			return null;
		}
		
		Collection<IoSession> sessions = ((AbstractSocketService)rs).getManagedSessions();
		if (sessions == null) {
			ci.println("ERROR: there are no sessions found for id '" + rsId + "'.");
			return null;
		}
		
		List<IoSession> ssto = new ArrayList<IoSession>();
		// find session
		for (IoSession s : sessions) {
			String sessionStr = (String)s.getAttribute(FrameworkConstants.SESSION_ID_FOR_RS);
			if (sessionId.equals(sessionStr)) {
				ssto.add(s);
			}
		}
		return ssto;
	}
	
	/**
	 * 用S查找服务
	 * 
	 * @param id
	 * @return
	 */
	private String getRSsFromId(String id) {
		long endpointId = Long.parseLong(id);
		Collection<RegisteredService> rss = getRegisteredServices(endpointId);
		if (rss != null) {
			return RegisteredServiceProperty.toString(getRegisteredServiceProperties(rss), true);
		}
		return null;
	}
	
	/**
	 * 显示未处理完成的task（即没有收到result）
	 * 
	 * @param ci
	 */
	public void _nor(CommandInterpreter ci) {
		RegisteredServiceFindService findService = getRegisteredServiceFindService();
		if (findService == null) {
			ci.println("ERROR: Can't find services.");
			return;
		}
		String idStr = ci.nextArgument();
		if (idStr == null) {
			ci.println("ERROR: USAGE: [nor rsid]");
			return;
		}
		
		String all = ci.nextArgument();
		
		long id = Long.parseLong(idStr);
		RegisteredService rs = findService.getRegisteredService(id);
		if (rs == null) {
			ci.println("ERROR: Can't find RS by id '" + id + "'.");
			return;
		}
		
		Map<String, Task> tasks = rs.getNoResultTasks();
		StringBuffer b = new StringBuffer();
		
		if ("all".equalsIgnoreCase(all)) {
			for (Entry<String, Task> entry : tasks.entrySet()) {
				String key = entry.getKey();
				Task task = entry.getValue();
				
				b.append(key).append("\n\t").append(task.toString());
				b.append("\n");
			}
		} else {
			int i = 0;
			for (Task task : tasks.values()) {
				b.append(task.getTaskId()).append("  ");
				i++;
				if (i % 3 == 0) {
					b.append("\n");
				}
			}
		}
		ci.println(b.toString());
	}
	
	/**
	 * TQ
	 * 
	 * @param ci
	 */
	public void _tq(CommandInterpreter ci) {
		RegisteredServiceFindService findService = getRegisteredServiceFindService();
		if (findService == null) {
			ci.println("ERROR: Can't find services.");
			return;
		}
		
		String idStr = ci.nextArgument();
		if (idStr == null) {
			ci.print(getTQtitle());
			Collection<RegisteredService> rss = findService.getRegisteredServices();
			if (rss != null) {						
				String t = "";						
				for (RegisteredService rs : rss) {
					if (!(rs instanceof AbstractRegisteredService)) {
						continue;
					}
					AbstractRegisteredService ars = (AbstractRegisteredService)rs;
					t = t + getTQforRS(ars);
				}
				ci.print(t);
			}
			
			return;
		}
		
		ci.print(getTQtitle());
		String[] ids = idStr.split(",");
		if (ids != null) {
			for (String str : ids) {				
				String t = "";
				Collection<RegisteredService> rss = findService.getRegisteredServices(Long.parseLong(str));
				if (rss != null) {
					for (RegisteredService rs : rss) {
						if (!(rs instanceof AbstractRegisteredService)) {
							continue;
						}
						
						AbstractRegisteredService ars = (AbstractRegisteredService)rs;				
						t = t + getTQforRS(ars);						
					}
				}
				
				ci.print(t);
			}
		}
	}
	
	/**
	 * accept queue
	 * 
	 * @param ci
	 */
	public void _aq(CommandInterpreter ci) {
		RegisteredServiceFindService findService = getRegisteredServiceFindService();
		if (findService == null) {
			ci.println("ERROR: Can't find services.");
			return;
		}
		
		String endpoints = ci.nextArgument();
		if (endpoints != null) {
			ci.print(getAQtitle());
			String[] eps = endpoints.split(",");
			if (eps != null) {
				for (String e : eps) {
					Collection<RegisteredService> rss = findService.getRegisteredServices(Long.parseLong(e));
					if (rss != null) {						
						String t = "";
						for (RegisteredService rs : rss) {
							t = t + getAQforRS(rs);
						}
						ci.print(t);
					}
				}
			}
						
			return;
		}
		
		Collection<RegisteredService> rss = findService.getRegisteredServices();
		if (rss != null) {
			ci.print(getAQtitle());
			String t = "";
			for (RegisteredService rs : rss) {
				t = t + getAQforRS(rs);
			}
			ci.print(t);
		}
	}
	
	private String getTQforRS(AbstractRegisteredService ars) {
		int tqSize = ars.getTaskQueue().size();
		int trqSize = ars.getTaskResultQueue().size();
		int stqSize = ars.getSendTaskQueue().size();
		int strqSize = ars.getSendTaskResultQueue().size();
		int pendingStqSize = ars.getPendingSendTaskSize();
		int noresultSize = ars.getNoResultTasks().size();
		String t = "";
		
		Collection<Endpoint> es = ars.getEndpoints();			
		for (Endpoint e : es) {
			String uri = e.getURI();			
			uri = uri.length() > 20 ? uri.substring(0, 20) : uri;
			String name = ars.getName();
			name = name.length() > 16 ? name.substring(0, 16) : name;
			
			String tn = String.format("%20s  %16s  %6s  %6s  %6s  %6s  %6s  %6s", 
					uri, name, tqSize, trqSize, stqSize, strqSize, pendingStqSize, noresultSize);
			t = t + tn + "\n";
		}
		
		return t;
	}
	
	private String getTQtitle() {
		String t = String.format("%20s  %16s  %6s  %6s  %6s  %6s  %6s  %6s", 
				"URI", "NAME", "TQ", "TRQ", "STQ", "STRQ", "PSTS", "NOR");
		t = t + "\n";
		for (int i = 0; i < 44; i ++) {
			t = t + "--";
		}
		t = t + "\n";
		return t;
	}
	
	/**
	 * uri  name  capcity size acceptable
	 * 
	 * @param rs
	 * @return
	 */
	private String getAQforRS(RegisteredService rs) {
		String t = "";
		Collection<Endpoint> es = rs.getEndpoints();
		for (Endpoint e : es) {
			String uri = e.getURI();
			uri = uri.length() > 20 ? uri.substring(0, 20) : uri;
			String name = rs.getName();
			name = name.length() > 16 ? name.substring(0, 16) : name;
			int capacity = rs.getWaitTaskMax();
			int accept = rs.acceptable();
			String tn = String.format("%20s  %16s  %8s  %4s  %10s", uri, name, capacity, capacity - accept, accept);
			t = t + tn + "\n";
		}
		
		return t;
	}
	
	private String getAQtitle() {
		String t = String.format("%20s  %16s  %8s  %4s  %10s", "URI", "NAME", "CAPACITY", "SIZE", "ACCEPTABLE");
		t = t + "\n";
		for (int i = 0; i < 34; i ++) {
			t = t + "--";
		}
		t = t + "\n";
		return t;
	}
	
	/**
	 * print thread stack of all threads
	 * 
	 * @param ci
	 */
	public void _pstall(CommandInterpreter ci) {
		
	}

	/**
	 * 服务信息查看命令
	 * 
	 */
	public void _rs(CommandInterpreter ci) {	
		Endpoint inEndpoint = null;		
		String commandOutput = null;
		
		String endpointURI = ci.nextArgument();
		if (endpointURI != null) { // 有参数
			if (endpointURI.endsWith("-l")) {
				// 注册服务集合
				commandOutput = RegisteredServiceProperty.toString(getAllRegisteredServiceProperties(), true);
			} else if (endpointURI.startsWith("uip://")) {
				inEndpoint = EndpointGenerator.generateFromURI(endpointURI);
				if (inEndpoint != null) {
					RegisteredService rs = getRegisteredService(inEndpoint); // 服务
					if (rs != null) {
						RegisteredServiceProperty rsp = getRSPropertyFromRS(rs); // 服务属性信息
                        if (rsp != null) {
                        	commandOutput = RegisteredServiceProperty.toStringDetail(rsp, getRSProperties(rs));
                        }						
					}
				}
			} else if (endpointURI.endsWith("-i")) {//用endpoint id
				String id = ci.nextArgument();
				commandOutput = getRSsFromId(id);
			} else if (endpointURI.endsWith("-f")) {//用interface id
				// interface id
				String interfaceIdStr = ci.nextArgument();
				Collection<RegisteredService> rss = getRegisteredServices(interfaceIdStr);
				if (rss != null) {
					commandOutput = RegisteredServiceProperty.toString(getRegisteredServiceProperties(rss), true);
				}				
			} else {
				Collection<RegisteredService> rss = new ArrayList<RegisteredService>();
				RegisteredService rsFind = getRegisteredService(Long.parseLong(endpointURI));
				if (rsFind != null) {
					rss.add(rsFind);
				}
				commandOutput = getRSSDescribes(rss);			
			}
		} else {
			// 注册服务集合
			commandOutput = RegisteredServiceProperty.toString(getAllRegisteredServiceProperties(), false);
		}
		
		ci.print(commandOutput);
	}
	
	/**
	 * 描述
	 * 
	 * @param rss
	 * @return
	 */
	private String getRSSDescribes(Collection<RegisteredService> rss) {
		StringBuffer b = new StringBuffer();
		for (RegisteredService rs : rss) {			
			RegisteredServiceProperty rsp = getRSPropertyFromRS(rs); // 服务属性信息
			if (rsp == null) {
				continue;
			}
			String s = RegisteredServiceProperty.toStringDetail(rsp, getRSProperties(rs));
			b.append(s);
		}
		
		return b.toString();
	}
	
	/**
	 * 查找与命令行输入名称相匹配的RS
	 * 
	 * @param ci
	 */
	public void _find(CommandInterpreter ci) {
		String nameRegion = ci.nextArgument();
		if (nameRegion == null) {
			ci.println("WARN: must input the name pattern.");
			return;
		}
		String commandOutput = null;
		nameRegion = nameRegion.toLowerCase();		
		List<RegisteredService> rsList = new ArrayList<RegisteredService>();
		
		Collection<RegisteredService> rss = getRegisteredServices();
		if (rss != null) {
			for (RegisteredService rs : rss) {
				String nameRS = rs.getName();
				nameRS = nameRS.toLowerCase();
				
				if (nameRS.indexOf(nameRegion) >= 0) {
					rsList.add(rs);
				}
			}
		}
		
		commandOutput = RegisteredServiceProperty.toString(getRegisteredServiceProperties(rsList), true);
		ci.print(commandOutput);
	}
	
	/**
	 * 查找指定名称的bundle
	 * 
	 * @param ci
	 */
	public void _fb(CommandInterpreter ci) {
		String nameRegion = ci.nextArgument();
		if (nameRegion == null) {
			ci.println("WARN: must input the name pattern.");
			return;
		}
		
		long bundleId = -1;
		
		try {
			bundleId = Long.parseLong(nameRegion);
		} catch (Exception e) {			
		}
		
		StringBuffer pb = new StringBuffer(); // 输出缓冲
		pb.append("ID").append("\t").append("STATE       BUNDLE").append("\n");

        if (bundleId >= 0) {
        	Bundle b = this.context.getBundle(bundleId);
        	if (b != null) {        		
        		pb.append(getBundleDescLabel(b));
        	}
        	ci.print(pb.toString());
        	return;
        }
        
        Bundle[] bundles = this.context.getBundles();
		if (bundles != null) {			
			for (Bundle bundle : bundles) {
				String nameRS = bundle.getSymbolicName();
				if (nameRS.indexOf(nameRegion) >= 0) {
				    pb.append(getBundleDescLabel(bundle));
				}
			}
		}
		
		ci.print(pb.toString());
    	return;
	}
	
	/**
	 * 查找指定名称的且发布了spring服务的bundle
	 * 
	 * @param ci
	 */
	public void _fs(CommandInterpreter ci) {		
		StateManage ssm = getStateManageService();
		if (ssm == null) {
			ci.print("Can't find 'StateManageService', you can't use the command in the moment.");
			return;
		}
		
		String nameRegion = ci.nextArgument();
		if (nameRegion == null) {
			ci.println("WARN: must input the name pattern.");
			return;
		}
		
		StringBuffer buffer = new StringBuffer();
		buffer.append(createStateStr("ID", "STATE", "BUNDLE"))
				      .append("\n");
		
		List<ServiceState> states = ssm.getStates();
		if (states != null) {
			for (ServiceState state : states) {
				String name = state.getBundleName();
				if (name.indexOf(nameRegion) >= 0) {
					buffer.append(createStateStr(String.valueOf(state.getBundleId()), state.getState().toString(), name)).append("\n");
				}				
			}
		}
		
		ci.print(buffer.toString());
	}
	
	/**
	 * bundle描述
	 * 
	 * @param b
	 * @return
	 */
	private String getBundleDescLabel(Bundle b) {
		String label = b.getSymbolicName();
		if (label == null || label.length() == 0) {
			label = b.toString();
		}
		return b.getBundleId() + "\t" + getBunleStateName(b) + label + "\n";
	}
	
	/**
	 * bundle状态名称
	 * 
	 * @param bundle
	 * @return
	 */
	private String getBunleStateName(Bundle bundle) {
		int state = bundle.getState();
		switch (state) {
			case Bundle.UNINSTALLED :
				return "UNINSTALLED "; 
			case Bundle.INSTALLED :
				return "INSTALLED   "; 
			case Bundle.RESOLVED :
				return "RESOLVED    "; 
			case Bundle.STARTING :
				return "STARTING    ";
			case Bundle.STOPPING :
				return "STOPPING    ";
			case Bundle.ACTIVE :
				return "ACTIVE      ";
			default :
				return Integer.toHexString(state);
		}
	}
	
	/**
	 * 获取指定endpoint的服务
	 * 
	 */
	private RegisteredService getRegisteredService(Endpoint endpoint) {
		RegisteredServiceFindService findService = getRegisteredServiceFindService();
		if (findService != null) {
			return findService.getRegisteredService(endpoint);
		}
		
		return null;
	}
	
	/**
	 * 指定接口ID的服务
	 * 
	 * @param interfaceId
	 * @return
	 */
	private Collection<RegisteredService> getRegisteredServices(String interfaceId) {
		RegisteredServiceFindService findService = getRegisteredServiceFindService();
		if (findService != null) {
			return findService.getRegisteredServices(interfaceId);
		}
		
		return null;
	}
	
	/**
	 * 指定接口ID的服务
	 * 
	 * @param interfaceId
	 * @return
	 */
	private Collection<RegisteredService> getRegisteredServices(long endpointId) {
		RegisteredServiceFindService findService = getRegisteredServiceFindService();
		if (findService != null) {
			return findService.getRegisteredServices(endpointId);
		}
		
		return null;
	}
	
	/**
	 * 所有的服务
	 * 
	 * @return
	 */
	private Collection<RegisteredService> getRegisteredServices() {
		RegisteredServiceFindService findService = getRegisteredServiceFindService();
		if (findService != null) {
			return findService.getRegisteredServices();
		}
		
		return null;
	}
	
	/**
	 * 指定bundleId的服务
	 * 
	 * @param controlId
	 * @return
	 */
	private RegisteredService getRegisteredService(long controlId) {
		RegisteredServiceFindService findService = getRegisteredServiceFindService();
		if (findService != null) {
			return findService.getRegisteredService(controlId);
		}
		
		return null;
	}
	
	/**
	 * 获取所有服务的属性
	 * 
	 * @return
	 */
	private List<RegisteredServiceProperty> getAllRegisteredServiceProperties() {
		List<RegisteredServiceProperty> rsps = new ArrayList<RegisteredServiceProperty>();
		Collection<RegisteredService> rss = getRegisteredServices();
		if (rss != null) {			
			for (RegisteredService rs : rss) {				
				RegisteredServiceProperty rsp = getRSPropertyFromRS(rs); // 服务属性信息	
				if (rsp != null) {
					rsps.add(rsp);
				}		
			}
		}
		
		return rsps;
	}
	
	/**
	 * 注册服务查找
	 * 
	 * @return
	 */
	private RegisteredServiceFindService getRegisteredServiceFindService() {
		ServiceReference sr = this.context.getServiceReference(RegisteredServiceFindService.class.getName());
		if (sr != null) {
			return (RegisteredServiceFindService)this.context.getService(sr);
		}
		
		return null;
	}
	
	/**
	 * 注册服务查找
	 * 
	 * @return
	 */
	private PropertiesConfigService getPropertiesConfigService() {
		ServiceReference sr = this.context.getServiceReference(PropertiesConfigService.class.getName());
		if (sr != null) {
			return (PropertiesConfigService)this.context.getService(sr);
		}
		
		return null;
	}
	
	/**
	 * 注册服务查找
	 * 
	 * @return
	 */
	private Map<String, String> getPropertiesConfigsFor(Bundle bundle) {
		PropertiesConfigService cs = getPropertiesConfigService();
		if (cs != null) {
			List<PropertiesConfig> ps = cs.get(bundle);
			if (ps != null) {
				Map<String, String> props = new LinkedHashMap<String, String>();
				for (PropertiesConfig p : ps) {
					Map<String, String> configs = p.getProperties();
					if (configs != null) {
						props.putAll(configs);
					}
				}
				
				return props;
			}
		}
		
		return null;
	}
	
	/**
	 * 获取服务属性信息
	 * 
	 * @param rs
	 * @return
	 */
	private RegisteredServiceProperty getRSPropertyFromRS(RegisteredService rs) {
		RegisteredServiceProperty rp = null;
		try {
		    rp = getRSPropertyFromRS0(rs);
		} catch (Throwable t) {
			return null;
		}
		
		return rp;
	}
	
	/**
	 * 获取服务属性信息
	 * 
	 * @param rs
	 * @return
	 */
	private RegisteredServiceProperty getRSPropertyFromRS0(RegisteredService rs) {
		RegisteredServiceProperty rsp = new RegisteredServiceProperty();
		
		rsp.setEndpoints(rs.getEndpoints()); // 端点
		rsp.setId(rs.getId()); // ID
		rsp.setName(rs.getName()); // 名称
		rsp.setLogConfig(rs.getLogConfiguration()); // 日志配置
		rsp.setRole(rs.getRole()); // 角色
		rsp.setTaskRecord(rs.getTaskRecord()); // 服务处理任务记录
		
		String starttime = (String)rs.getAttributes().getAttribute(FrameworkConstants.RS_ATTR_STARTTIME);// 启动时间
		if (starttime != null) {
			rsp.setStartTime(starttime);
		}
		
		rsp.setRs(rs);
		rsp.setBundle(rs.getBundleContext().getBundle());
		
		return rsp;
	}
	
	/**
	 * 获取指定服务的配置详细信息
	 * 
	 * @param rs
	 * @return
	 */
	private Map<String, String> getRSProperties(RegisteredService rs) {	
		Map<String, String> props = new LinkedHashMap<String, String>();
		ServiceReference rf = this.context.getServiceReference(PropertiesRepositoryService.class.getName());
        if (rf == null) {
        	return null;
        }
		PropertiesRepositoryService repository = (PropertiesRepositoryService) context.getService(rf);
        if (repository == null) {
        	return null;
        }
        
        String locations = ""; // 路径
        String bundleLocation = rs.getBundleContext().getBundle().getLocation(); // bundle路径
        List<String> propertiesLocations = repository.getPropertiesLocations(bundleLocation);		
		if (propertiesLocations != null) {
			for (String propertiesLocation: propertiesLocations) {
				locations = locations + propertiesLocation + ";";
			}
		}
		
		props.put("[ETC]", locations);
		
		Map<String, String> ps = getPropertiesConfigsFor(rs.getBundleContext().getBundle());
		if (ps != null) {
			props.putAll(ps);
		}
		return props;
	}
	
	public String getHelp() {
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("\trs   - print all register services.\n")
		      .append("\tfind - find the register services by name pattern.\n");
		buffer.append("\tsss - print all register services'states.\n");
		buffer.append("\t ps - print pakage usage.\n");
		buffer.append("\tinfo - print the pakage information details.\n");
		buffer.append("\tlt - print and list the tasks processing.\n");
		
		return buffer.toString();
	}
		
	/**
	 * 服务属性
	 * 
	 * @param rss
	 * @return
	 */
	private List<RegisteredServiceProperty> getRegisteredServiceProperties(Collection<RegisteredService> rss) {
		List<RegisteredServiceProperty> rsps = new ArrayList<RegisteredServiceProperty>();
		
		for (RegisteredService rs : rss) {
			RegisteredServiceProperty rsp = getRSPropertyFromRS(rs);
			if (rsp != null) {
				rsps.add(rsp);
			}					
		}
		
		return rsps;
	}
	
	/**
	 * 对配置文件密码加密
	 * 
	 * @param ci
	 */
	public void _encrypt(CommandInterpreter ci) {
		EncryptorService encrypt;
		ServiceReference sr = this.context.getServiceReference(EncryptorService.class.getName());
		if (sr != null) {
			encrypt = (EncryptorService) this.context.getService(sr);
		} else {
			ci.println("加密服务未注册.");
			return;
		}

		if (encrypt == null) {
			ci.println("加密服务未启动.");
			return;
		}

		String cmd = ci.nextArgument();
		if (StringUtils.hasText(cmd)) {
			ci.println(encrypt.encrypt(cmd));
		} else {
			ci.println("请输入要加密的字符串.");
		}
	}

	/**
	 * 对配置文件密码解密
	 * 
	 * @param ci
	 */
	public void _decrypt(CommandInterpreter ci) {
		EncryptorService encryptor;
		ServiceReference sr = this.context.getServiceReference(EncryptorService.class.getName());
		if (sr != null) {
			encryptor = (EncryptorService) this.context.getService(sr);
		} else {
			ci.println("解密服务未注册.");
			return;
		}

		if (encryptor == null) {
			ci.println("解密服务未启动.");
			return;
		}

		String cmd = ci.nextArgument();
		if (StringUtils.hasText(cmd)) {
			if (encryptor.isEncryptedValue(cmd)) {
				ci.println(encryptor.decrypt(cmd));
			} else {
				ci.println(encryptor.decrypt("ENC(" + cmd + ")"));
			}
		} else {
			ci.println("请输入要解密的字符串.");
		}
	}
}
